<template>
  <div class="line-Loss">
    <el-tabs
      v-model="activeName3"
      :tab-position="tabPosition"
      class="line-Loss-w"
      @tab-click="tabClickPid"
    >
      <el-tab-pane
        v-for="(item, index1) in tabData"
        :label="item.name + (item.position ? '[' + item.position + ']' : '')"
        :name="
          index1 + '-' + (item.position ? item.position : '') + '-' + item.type
        "
      >
        <template v-if="item.children.length > 0">
          <el-tabs
            v-model="activeName2"
            :tab-position="tabPosition"
            class="tabs-scroll tabs-scroll-w"
            @tab-click="tabClick"
          >
            <el-tab-pane
              class="ll-tab"
              v-for="(item1, index) in item.children"
              :label="item1.name + '[' + item1.position + ']'"
              :name="item1.type + '-' + item1.position + '-' + index"
            >
              <!-- {{ activeName2 }}:{{
                item1.type + "-" + item1.position + "-" + index
              }} -->

              <div class="ll-btn1">
                <template v-if="item1.name === '采集终端'">
                  <Collect
                    :currentData="item1"
                    :position="item1.position + ''"
                    ref="collectRef"
                    @changeActiveName="changeActiveName"
                    :activeName1="activeName1"
                  ></Collect>
                </template>
                <template v-else>
                  <Summary
                    :currentData="item1"
                    :position="item1.position + ''"
                    ref="summaryRef"
                  ></Summary>
                </template>
              </div>
              <div
                :class="
                  'll-btn2 ' + (item1.name === '采集终端' ? '' : 'll-btn2-1')
                "
                v-if="isAll === '1'"
              >
                <el-button @click="clearSubmitAll">恢复全部故障</el-button>
                <el-button @click="handleSubmitAll">设置全部故障</el-button>
              </div>
            </el-tab-pane>
          </el-tabs>
        </template>
        <template v-else>
          <div style="display: flex">
            <div class="ll-btn1">
              <Summary
                :currentData="item"
                ref="summaryRef"
                :position="item.position + ''"
              ></Summary>
            </div>
            <div class="ll-btn2 ll-btn2-1">
              <el-button @click="clearSubmitAll">恢复全部故障</el-button>
              <el-button @click="handleSubmitAll">设置全部故障</el-button>
            </div>
          </div>
        </template>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import { lineLossData } from "@/gm/meterLabel.js";
import { useAppStore, faultSubListStore } from "@/stores";
import Communication from "@/components/communication.vue";
import TerminalAmmeter from "@/components/terminalAmmeter.vue";
import Collect from "./collect.vue";
import Summary from "./summary.vue";
import { storeToRefs } from "pinia";
import {
  meterPositionListSet,
  meterRelayFault,
  meterJzqFault,
  meterRelayFaultRecoveryAll,
  meterJzqFaultRecoveryAll,
  meterCommParmFalut,
  meterApplyMeterAddress,
  terminalSelectByPos,
  measuringPointParameterFaultSave,
  measuringPointParameterMeterParam,
  meterCldParmFalut,
  meterFzbFault,
  meterFzbSingleFault,
} from "@/api/source.js";

const useApp = useAppStore();
let {
  organStructure,
  tableFaultSetting,
  tableVoltage,
  meterCurrent,
  tableFault,
  currentPlanId,
  isSuccess,
  faultLoading,
} = storeToRefs(useApp);
const faultSubList = faultSubListStore();
let { faultSubData } = storeToRefs(faultSubList);
// console.log("faultSubList123", faultSubData);

const tabPosition = ref("left");
const activeName = ref("first");
const tabData = ref([
  {
    label: "台区1",
    value: 1,
    children: [
      {
        label: "采集终端",
        value: 1,
      },
      {
        label: "总表",
        value: 2,
      },
    ],
  },
  {
    label: "台区2",
    value: 2,
    children: [
      {
        label: "采集终端",
        value: 21,
      },
      {
        label: "总表",
        value: 22,
      },
    ],
  },
]);
const tableData = lineLossData;
const radio = ref(1);
const lists = ref();
const activeName1 = ref("1");
const activeName1Temp = ref("1");
const activeName2 = ref();
const activeName3 = ref("");
const collectRef = ref();
const summaryRef = ref();
const isAll = ref("1");
const bJI = ref(0);
const bwI = ref(0);
let successNum = ref(0);
let errorNum = ref(0);
const flagClear = ref(false);
//数据初始化
onMounted(() => {
  lists.value = faultSubData.value[7]; //初始化数据
  watch(
    tableFault,
    (newValue, oldValue) => {
      tabData.value = newValue;
      let result = loopDataUI(tabData.value, []);
      tableVoltage.value = result;
      meterCurrent.value = result;
      if (tabData.value[0]) {
        activeName2.value =
          tabData.value[0].children[0].type +
          "-" +
          tabData.value[0].children[0].position +
          "-0";
        activeName3.value =
          "0-" +
          (tabData.value[0].position ? tabData.value[0].position : "") +
          "-" +
          tabData.value[0].type;
      }
    },
    { immediate: true },
    { deep: true }
  );
  watch(
    activeName3,
    (newValue, oldValue) => {
      if (newValue) {
        let arr = newValue.split("-");
        // console.log("activeName3", arr);
        if (!arr[1]) {
          if (tabData.value[arr[0]]) {
            activeName2.value =
              tabData.value[arr[0]].children[0].type +
              "-" +
              tabData.value[arr[0]].children[0].position +
              "-0";
          }
        }
      }
    },
    { immediate: true },
    { deep: true }
  );
  watch(
    activeName2,
    (newValue, oldValue) => {
      if (newValue) {
        let arr = newValue.split("-");
        // console.log("watch", arr, collectRef.value);
        if (arr[0] === "2" || arr[0] === "6") {
          if (collectRef.value != undefined && collectRef.value != "undefined")
            collectRef.value[arr[2]].init(arr[1]);
        } else {
          if (summaryRef.value != undefined && summaryRef.value != "undefined")
            summaryRef.value[arr[2] - 1].init(arr[1]);
        }
      }
    },
    { immediate: true },
    { deep: true }
  );
  watch(isSuccess, (newValue, oldValue) => {
    if (!newValue) {
      let tab1 = loopData(tabData.value, [], 1); //终端
      let tab2 = loopData(tabData.value, [], 0); //表位
      let num = tab1.length;
      let num2 = tab2.length;
      if (++bJI.value && bJI.value < num) {
        if (flagClear.value) {
          doCollectClear(tab1, bJI.value, tab1.length);
        } else {
          doCollectSubmit(tab1, bJI.value, num);
        }
      }
      if (bJI.value === num) {
        if (flagClear.value) {
          //是否取消
          doSummaryClear(tab2, 0, tab2.length);
        } else {
          doSummarySubmit(tab2, 0, num2);
        }
      } else {
        if (bwI.value > 0 || bJI.value === Number(num) + 1) {
          if (++bwI.value && bwI.value < num2) {
            if (flagClear.value) {
              doSummaryClear(tab2, bwI.value, num2);
            } else {
              doSummarySubmit(tab2, bwI.value, num2);
            }
          }
        }
      }

      if (bwI.value === num2) {
        faultLoading.value = false;
      }
      // console.log("watch1", num, bJI.value, bwI.value);
    }
    // console.log("watch2", newValue, bJI.value, bwI.value);
  });
  // meterPositionListSetApi();
});
//表位故障
const meterPositionListSetApi = async () => {
  let parm = {
    planId: currentPlanId.value,
  };
  await meterPositionListSet(parm)
    .then((res) => {
      tabData.value = res.data;
    })
    .catch((err) => {
      console.log(err);
    });
};
//计算表位电压、电流 tableVoltage meterCurrent
const loopDataUI = (dataTab = [], tempArr) => {
  let arr = [3, 4, 7, 8];
  dataTab.forEach((item) => {
    if (arr.includes(item.type)) {
      item.voltagePhase = "U_ABC";
      item.currentPhase = "I_ABC";
      tempArr.push(item);
    }
    if (item.children != undefined && item.children.length > 0) {
      loopDataUI(item.children, tempArr);
    }
  });
  return tempArr;
};
//设置全部故障
const handleSubmitAll = () => {
  flagClear.value = false;
  let tab1 = loopData(tabData.value, [], 1); //终端
  doCollectSubmit(tab1, 0, tab1.length);
};
const loopData = (dataTab = [], tempArr, type) => {
  let arr = [3, 4, 7, 8];
  if (type === 1) arr = [2, 6];
  dataTab.forEach((item) => {
    if (arr.includes(item.type)) {
      tempArr.push(item);
    }
    if (item.children != undefined && item.children.length > 0) {
      loopData(item.children, tempArr, type);
    }
  });
  return tempArr;
};
const doCollectSubmit = (data, i, num) => {
  faultLoading.value = true;
  let parm = data[i].position;
  if (collectRef.value[i]) {
    collectRef.value[i].handleSubmit(data[i]);
    bJI.value = i;
  }
};
const doSummarySubmit = (data, i, num) => {
  let parm = data[i].position;
  if (summaryRef.value[i]) {
    summaryRef.value[i].handleSubmit(data[i]);
    bwI.value = i;
  }
};
//恢复全部故障
const clearSubmitAll = () => {
  flagClear.value = true;
  let tab1 = loopData(tabData.value, [], 1); //终端
  let tab2 = loopData(tabData.value, [], 0); //表位
  doCollectClear(tab1, 0, tab1.length);
  // doSummaryClear(tab2, 0, tab2.length);
};
const doCollectClear = (data, i, num) => {
  let parm = data[i].position;
  if (collectRef.value[i]) {
    collectRef.value[i].clearSubmit(data[i]);
    bJI.value = i;
  }
};
const doSummaryClear = (data, i, num) => {
  let parm = data[i].position;
  if (summaryRef.value[i]) {
    summaryRef.value[i].clearSubmit(data[i]);
    bwI.value = i;
  }
};
const changeActiveName = (val) => {
  activeName1.value = val;
  activeName1Temp.value = val;
  isAll.value = activeName1.value;
};
const tabClick = (obj) => {
  let arr = obj.props.name.split("-");
  if (arr[0] === "2" || arr[0] === "6") {
    isAll.value = activeName1.value;
  } else {
    isAll.value = "1";
  }
};
const tabClickPid = (obj) => {
  let arr = obj.props.name.split("-");
  if (arr[2] === "5") {
    activeName1.value = "1";
    isAll.value = "1";
  } else {
    isAll.value = activeName1Temp.value;
    activeName1.value = activeName1Temp.value;
  }
};
</script>
<style lang="scss" scoped>
//功率源
.line-Loss {
  .ll-tab {
    display: flex;
  }
  .ll-content {
    display: flex;
    .ll-bw {
      display: flex;
      justify-content: space-around;
      .ll-bw-item1 {
        display: flex;
        flex-direction: column;
        padding: 2px 10px;
      }
      .ll-bw-item2 {
        display: flex;
      }
    }
    .ll-bj {
      display: flex;
      justify-content: space-around;
    }
    .el-checkbox.el-checkbox--large {
      height: 24px;
    }
    .el-radio {
      height: 23px;
    }
    .item-border {
      border: 1px solid #ebeef5;
      margin: 2px 10px;
    }
    .item {
      display: flex;
      flex-direction: column;
      padding: 2px 10px;
    }
  }
  .ll-btn1 {
    flex-grow: 1;
  }
  // .ll-btn2 {
  //   width: 100px;
  //   display: flex;
  //   flex-direction: column;
  //   align-items: end;
  //   justify-content: end;
  //   margin-bottom: 10px;
  //   .el-button {
  //     width: 90px;
  //     margin-top: 10px;
  //   }
  // }
}
</style>
<style lang="scss">
.tabs-scroll {
  .el-tabs__header {
    .el-tabs__nav {
      height: 500px;
      overflow: auto;
    }
  }
  .ll-btn1 {
    .el-tabs__nav {
      height: auto;
      overflow: hidden;
    }
  }
}
</style>
